package com.shi.yibanjia.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shi.yibanjia.annotation.Auth;
import com.shi.yibanjia.annotation.MyLog;
import com.shi.yibanjia.common.Result;
import com.shi.yibanjia.entity.dto.UserPageQueryDto;
import com.shi.yibanjia.entity.po.User;
import com.shi.yibanjia.enums.AuthCodeEnum;
import com.shi.yibanjia.enums.LogType;
import com.shi.yibanjia.service.UserService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/admin/customer")
public class UserController {

    @Resource
    private UserService userService;

    @GetMapping("/{page}/{size}")
    @Auth(hasPerm = AuthCodeEnum.BIZ_CUSTOMER_DQL)
    @Cacheable(value = "yibanjia:customer", key = "'page:'+#page+':size:'+#size")
    public Result getUserList(@PathVariable("page") Integer page,
                              @PathVariable("size") Integer size,
                              UserPageQueryDto userPageQueryDto) {
        String key = userPageQueryDto.getKey();
        Page<User> userPage = userService.page(new Page<>(page, size), new LambdaQueryWrapper<User>()
                .like(StrUtil.isNotBlank(key), User::getNickname, key)
                .or()
                .like(StrUtil.isNotBlank(key), User::getPhone, key)
                .orderByDesc(User::getLastLoginTime));
        return Result.ok(userPage);
    }

    @MyLog(type = LogType.DELETE)
    @DeleteMapping
    @Auth(hasPerm = AuthCodeEnum.BIZ_CUSTOMER_DML)
    @CacheEvict(value = "yibanjia:customer", allEntries = true)
    public Result batchRemove(@RequestBody List<Long> ids) {
        userService.removeBatchByIds(ids, 10, false);
        return Result.ok();
    }

    @MyLog(type = LogType.UPDATE)
    @PutMapping("/{id}/{isEnabled}")
    @Auth(hasPerm = AuthCodeEnum.BIZ_CUSTOMER_DML)
    @CacheEvict(value = "yibanjia:customer", allEntries = true)
    public Result updateUserStatus(@PathVariable("id") Long id,
                                   @PathVariable("isEnabled") Integer isEnabled) {
        userService.update(new LambdaUpdateWrapper<User>()
                .set(User::getIsEnabled, isEnabled)
                .eq(User::getId, id));
        return Result.ok();
    }

    /**
     * 批量导出
     *
     * @param ids
     * @return
     */
    @MyLog
    @PostMapping("/export")
    @Auth(hasPerm = AuthCodeEnum.BIZ_CUSTOMER_EXPORT)
    public void exportExcel(@RequestBody List<Long> ids, HttpServletResponse response) {
        List<User> userList = userService.listByIds(ids);
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            EasyExcel.write(response.getOutputStream(), User.class)
                    .autoCloseStream(true).build()
                    .write(() -> userList, new WriteSheet()).finish();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Auth(hasPerm = AuthCodeEnum.BIZ_CUSTOMER_DML)
    @GetMapping("/count")
    @Cacheable(value = "yibanjia:customer", key = "'count'")
    public Result getCount() {
        return Result.ok(userService.count());
    }
}
